package ginx

import (
	"bytes"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/gookit/color"
	"io"
	"net/http"
)

type Response struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    any    `json:"data"`
}

func BodyJsonWithErr[T any](ctx *gin.Context, v *T) bool {
	color.Grayln("-------- Log:Request ---------")
	all, err := io.ReadAll(ctx.Request.Body)
	if err != nil {
		res := Response{
			Code:    500,
			Message: "ErrTypeInvalidParams",
			Data:    err,
		}
		ctx.AbortWithStatusJSON(http.StatusOK, res)
		return true
	}
	color.Grayln(string(all))
	color.Grayln("=== Body End ====")
	//err = ctx.ShouldBindJSON(v)
	err = json.Unmarshal(all, v)
	if err != nil {
		res := Response{
			Code:    500,
			Message: err.Error(),
			Data:    err,
		}
		ctx.AbortWithStatusJSON(http.StatusOK, res)
		return true
	}
	ctx.Request.Body = io.NopCloser(bytes.NewReader(all))
	color.Grayf("- requestnot null; type:%T\n", *v)
	color.Grayf("- request json:%+v\n", *v)
	color.Grayln("-------- Log:Request End --------")
	return false
}

type IRouterInit interface {
	InitRouter(group *gin.RouterGroup)
}
type RouterInits []IRouterInit

func NewRouterInits(routes ...IRouterInit) RouterInits {
	return routes
}
func HandleRouterInit(group *gin.RouterGroup, vs ...IRouterInit) {
	for _, ok := range vs {
		ok.InitRouter(group)
	}
}
func NewRouters(router ...IRouterInit) []IRouterInit {

	return router
}

func AbortErrWith(ctx *gin.Context, code int, message string, data any) {
	ctx.AbortWithStatusJSON(200, Response{code, message, data})
}
